<script setup lang="ts">
import { usePrefix } from '@season-designable/vue';
import ImageInput from './index.vue';

const prefix = usePrefix('background-style-setter');
const props = defineProps(['value']);
const emit = defineEmits(['change']);

const addBgValue = (value: any) => {
  if (/url\([^)]+\)/.test(value)) {
    return value;
  }
  return `url(${value})`;
};

const getBackgroundUrl = (background?: string) => {
  let regBackgroundUrl = /url\("?'?.*"?'?\)/g;
  let regReplace = /"|'|url|\(|\)/g;
  if (background && background.match(regBackgroundUrl)) {
    return background.match(regBackgroundUrl)?.[0].replace(regReplace, '');
  }

  return '';
};

const handleChange = (url: string) => {
  emit('change', addBgValue(url));
};
</script>

<template>
  <div :class="prefix">
    <ImageInput :value="getBackgroundUrl(props.value)" @change="handleChange" />
  </div>
</template>

<style lang="scss" scoped>
@import '../../../../styles.scss';

.dn-input-items {
  display: flex;
  flex-wrap: wrap;
  margin-left: -8px;
}
</style>
